package com.xzsoft.gdwz.jwt.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import xz.facade.user.model.Result;

import com.xzsoft.gdwz.jwt.util.AccessToken;
import com.xzsoft.gdwz.jwt.util.JwtHelper;
import com.xzsoft.gdwz.model.UserToken;
import com.xzsoft.gdwz.services.RefreshTokenServices;
import com.xzsoft.gdwz.util.MD5;
import com.xzsoft.gdwz.util.Tools;

@Controller
public class JsonWebToken {
	
	Logger logger = Logger.getLogger(JsonWebToken.class);
	
	@Autowired
	private RefreshTokenServices refreshTokenServices;
	
	private static final long TTLMillis = 86400000;
	
	private static final String issuer = "GDWZ";
	
	@RequestMapping("/oauth/accessToken")
	public void getAccessToken(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type","text/html;charset=UTF-8");
		try
		{
			Result result = new Result();
			String username=request.getParameter("username");
			if(username == null||"".equals(username)){
				result.setResult("");
				result.setResultCode("C0003");
				result.setResultMessage("用户名不能为空！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
				return ;
			}
			String password = request.getParameter("password");
			if(password == null||"".equals(password)){
				result.setResult("");
				result.setResultCode("C0004");
				result.setResultMessage("密码不能为空！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
				return ;
			}
			//校验用户名密码
			UserToken token = refreshTokenServices.getToken(username,password);
			if(token == null){
				result.setResult("");
				result.setResultCode("C0005");
				result.setResultMessage("用户名或密码错误！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
				return ;
			}
			
			//时间解析   
			String timestamp = request.getParameter("timestamp");
			if(timestamp == null || "".equals(timestamp)){
				result.setResult("");
				result.setResultCode("C0006");
				result.setResultMessage("时间戳不能为空！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
		    	return ;
			}
			
			DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");  
			DateTime remoteTimestamp = null;
			try {
				remoteTimestamp = DateTime.parse(timestamp, format);
			} catch (Exception e) {
				result.setResult("");
				result.setResultCode("C0007");
				result.setResultMessage("时间戳格式错误！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
		    	return ;
			}
			DateTime localtimestamp = new DateTime();
			int local = localtimestamp.getMinuteOfDay();
			int remote = remoteTimestamp.getMinuteOfDay();
			int temp = Math.abs(local - remote);
			logger.info("时间相差："+temp);
			if(temp>30){
				result.setResult("");
				result.setResultCode("C0008");
				result.setResultMessage("时间相差大于30分钟！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
		    	return ;
			}
			
			//校验sign
			String remoteSign = request.getParameter("sign");
			String localsign = username+timestamp+ password;
			localsign = MD5.GetMD5Code(localsign).toUpperCase();
			String macAddress = Tools.getLocalMac();
			if(!localsign.equals(remoteSign)){
				result.setResult("");
				result.setResultCode("C0009");
				result.setResultMessage("sign不正确！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
		    	response.getWriter().println(jb.toString());
		    	return ;
			}
			
			//拼装accessToken
			String accessToken = JwtHelper.createJWT(username, password,
					username,timestamp,macAddress,remoteSign, issuer,TTLMillis);
			
			//返回accessToken
			AccessToken accessTokenEntity = new AccessToken();
			accessTokenEntity.setAccess_token(accessToken);
			accessTokenEntity.setExpires_in(TTLMillis);
			accessTokenEntity.setTime(localtimestamp.toString("yyyy-MM-dd HH:mm:ss"));
			result.setResult(accessTokenEntity);
			result.setSuccess(true);
			response.getWriter().print(JSONObject.fromObject(result).toString());
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}finally{
			response.getWriter().flush();
			response.getWriter().close();
		}
		
	}
	
}
